<template>
  <div class="scoring-container">
    <!-- 上部信息区域 -->
    <div class="top-section">
      <div class="left-info">
        <div class="info-item"><span class="label">试卷名称：</span>{{ paperInfo.name }}</div>
        <div class="info-item"><span class="label">年级：</span>{{ paperInfo.grade }}</div>
        <div class="info-item"><span class="label">科目：</span>{{ paperInfo.subject }}</div>
      </div>
      <div class="right-info">
        <div class="info-item"><span class="label">学生姓名：</span>{{ studentInfo.name }}</div>
        <div class="info-item total-score">
          <span class="label">总分：</span>
          <span class="score-value">{{ totalScore }}</span>
        </div>
      </div>
    </div>

    <!-- 下部题目评分区域 -->
    <div class="bottom-section">
      <!-- 选择题区域 -->
      <div class="question-column choice-column">
        <h3 class="column-title">
          <span>选择题 (共 {{ choiceQuestions.length }} 题)</span>
          <span>得分：{{ choiceScores }} / {{ choiceTotalScore }}</span>
        </h3>
        <div class="question-list">
          <div v-for="(q, index) in choiceQuestions" :key="q.id" class="question-item">
            <div class="question-header">
              <span class="question-number">{{ index + 1 }}.</span>
              <el-tag :type="q.isMultiple ? 'success' : 'primary'" size="small">
                {{ q.isMultiple ? '多选题' : '单选题' }}
              </el-tag>
              <span class="question-score">({{ q.score }}分)</span>
              <el-tag :type="judgeCorrect(q)  ? 'success' : 'danger'" size="small">
                {{ judgeCorrect(q) ? '正确' : '错误' }}
              </el-tag>
            </div>
            <div class="question-stem">{{ q.info.name }}</div>
            <!-- 选项区域 -->
            <div class="question-options" v-if="q.info.options && q.info.options.length">
                 <el-checkbox-group v-model="q.info.multipleAnswers" disabled v-if="q.info.isMultiple"  >
                    <div v-for="(option, index) in q.info.options" :key="index" class="option-item">
                      <div class="option-selector">
                        <el-checkbox :label="option.label" :key="option.value" :value="option.value" />
                      </div>
                    </div>
                  </el-checkbox-group>
                  <el-radio-group  v-model="q.info.singleAnswer" disabled v-if="!q.info.isMultiple" >
                    <div v-for="(option, index) in q.info.options" :key="index" class="option-item">
                      <div class="option-selector">
                        <el-radio :label="option.label" :key="option.value" :value="option.value" />
                      </div>
                    </div>
                  </el-radio-group>
            </div>

            <!-- 答案解析 -->
            <div class="answer-analysis">
              <div class="right-answer" v-if="q.info.referenceAnswer">参考答案： {{  q.info.referenceAnswer }}</div> 
              <strong>答案解析：</strong>{{ q.answerInfo }}
            </div>

            <!-- 关联知识点 -->
            <div class="knowledge-points" v-if="q.info.knowledgePoints && q.info.knowledgePoints.length">
              <strong>关联知识点：</strong>
              <el-tag v-for="point in q.info.knowledgePoints" :key="point.id" size="small" class="knowledge-tag">{{ point.name }}</el-tag>
            </div>

            <!-- 老师评语 -->
            <div class="teacher-comment">
              <el-input
                v-model="q.comment"
                :disbaled="mode == 'student'"
                placeholder="请输入评语（学生可见）"
                type="textarea"
                :rows="2"
              ></el-input>
            </div>
          </div>
        </div>
      </div>

      <!-- 填空题区域 -->
      <div class="question-column fill-column">
        <h3 class="column-title">
          <span>填空题 (共 {{ fillQuestions.length }} 题)</span>
          <span>得分：{{ fillScores }}  / {{ fillTotalScore }}</span>
        </h3>
        <div class="question-list">
          <div v-for="(q, index) in fillQuestions" :key="q.id" class="question-item">
            <div class="question-header">
              <span class="question-number">{{ index + 1 }}.</span>
              <span class="question-score">({{ q.score }}分)</span>
              <div class="judgment-buttons">
                <el-radio v-model="q.judgment" label="correct" @change="calculateScore">正确</el-radio>
                <el-radio v-model="q.judgment" label="incorrect" @change="calculateScore">错误</el-radio>
              </div>
            </div>
           <div class="question-stem">{{ q.info.name }}</div>

            <!-- 学生答案 -->
            <div class="student-answers">
              <div  class="answer-item">  
                <span class="answer-content">学生答案：{{ q.info.singleAnswer }}</span>    
              </div>
            </div>

            <!-- 答案解析 -->
            <div class="answer-analysis">
              <div class="right-answer" v-if="q.info.referenceAnswer">参考答案： {{  q.info.referenceAnswer }}</div> 
              <strong>答案解析：</strong>{{ q.answerInfo }}
            </div>

            <!-- 关联知识点 -->
            <div class="knowledge-points" v-if="q.info.knowledgePoints && q.info.knowledgePoints.length">
              <strong>关联知识点：</strong>
              <el-tag v-for="point in q.info.knowledgePoints" :key="point.id" size="small" class="knowledge-tag">{{ point.name }}</el-tag>
            </div>

            <!-- 老师评语 -->
            <div class="teacher-comment">
              <el-input
                v-model="q.comment"
                :disbaled="mode == 'student'"
                placeholder="请输入评语（学生可见）"
                type="textarea"
                :rows="2"
              ></el-input>
            </div>
          </div>
        </div>
      </div>

      <!-- 解答题区域 -->
      <div class="question-column answer-column">
        <h3 class="column-title">
          <span>解答题 (共 {{ answerQuestions.length }} 题)</span>
          <span>得分：{{ answerScores }} / {{ answerTotalScore }}</span>
        </h3>
        <div class="question-list">
          <div v-for="(q, index) in answerQuestions" :key="q.id" class="question-item">
            <div class="question-header">
              <span class="question-number">{{ index + 1 }}.</span>
              <span class="question-score">({{ q.score }}分)</span>
              <div class="judgment-buttons">
                <el-radio v-model="q.judgment" label="correct" @change="calculateScore">正确</el-radio>
                <el-radio v-model="q.judgment" label="incorrect" @change="calculateScore">错误</el-radio>
              </div>
            </div>
            <div class="question-stem">{{ q.info.name }}</div>

            <!-- 学生答案 -->
            <div class="student-answer">
              <strong>学生答案：</strong>
              <div class="answer-content">{{ q.studentAnswer }}</div>
            </div>

            <!-- 参考答案 -->
            <div class="reference-answer">
              <strong>参考答案：</strong>
              <div class="answer-content">{{ q.info.referenceAnswer }}</div>
            </div>

            <!-- 答案解析 -->
            <div class="answer-analysis">
              <strong>答案解析：</strong>{{ q.answerInfo }}
            </div>

            <!-- 关联知识点 -->
            <div class="knowledge-points" v-if="q.info.knowledgePoints && q.info.knowledgePoints.length">
              <strong>关联知识点：</strong>
              <el-tag v-for="point in q.info.knowledgePoints" :key="point.id" size="small" class="knowledge-tag">{{ point.name }}</el-tag>
            </div>

            <!-- 老师评语 -->
            <div class="teacher-comment">
              <el-input
                v-model="q.comment"
                :disbaled="mode == 'student'"
                placeholder="请输入评语（学生可见）"
                type="textarea"
                :rows="3"
              ></el-input>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions" v-if="mode == 'teacher'">
      <el-button type="primary" @click="cancelScores">取消评分</el-button>
      <el-button type="success" @click="submitScores">提交评分</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElTag, ElCheckbox, ElRadio, ElInput, ElButton, ElMessage } from 'element-plus';

import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();


let mode = ref('teacher');

// 接收父组件传入的试卷和学生信息
const props = defineProps({
  
  paperInfo: {
    type: Object,
    required: true,
    default: () => ({
      name: '默认试卷',
      grade: '高一',
      subject: '数学'
    })
  },
  studentInfo: {
    type: Object,
    required: true,
    default: () => ({
      name: '未知学生',
      answers: {}
    })
  },
  questions: {
    type: Array,
    required: true,
    default: () => []
  }
});

// 处理题目数据，添加评分相关属性
const processedQuestions = ref([]);

onMounted(() => {
  // 初始化模式
  if (route.query.mode == 'student') {
    mode.value = 'student';
  }
 
  // 初始化题目数据，添加评分所需属性
  processedQuestions.value = props.questions.map(q => {
    // 为不同题型添加不同的评分属性
    if (q.type === 'choice') {
      // 选择题 - 自动判断
      const isCorrect = checkChoiceAnswer(q, props.studentInfo.answers[q.id]);
      return {
        ...q,
        isCorrect,
        comment: '',
        studentAnswers: props.studentInfo.answers[q.id] || [],
        options: q.options.map(opt => ({
          ...opt,
          isSelected: props.studentInfo.answers[q.id]?.includes(opt.id) || false,
          isCorrect: q.referenceAnswer.includes(opt.id)
        }))
      };
    } else if (q.type === 'fill') {
      // 填空题 - 手动判断
      return {
        ...q,
        judgment: null,
        comment: '',
        studentAnswers: props.studentInfo.answers[q.id] || []
      };
    } else if (q.type === 'answer') {
      // 解答题 - 手动判断
      return {
        ...q,
        judgment: null,
        comment: '',
        studentAnswer: props.studentInfo.answers[q.id] || ''
      };
    }
    return q;
  });

  // 初始化总分
  calculateScore();
});


// 先试用mockData  数据 模拟
const mockData = {
  name: '默认试卷',
  area: '安徽-合肥',
  grade: '高一',
  subject: '数学',
  examTime: 60, // 考试时间，单位分钟
  questions: { // 题目
    choice: [
        {
            id: 1,
            content: '1', // 关联的是题目的id 
            score: 10,
            info: {
                name: '选择1',   // 题目题干
                description: '', // 题目描述
                type: 'choice',
                options: [
                    { label: '选项A', value: 'A' },
                    { label: '选项B', value: 'B' },
                    { label: '选项C', value: 'C' },
                    { label: '选项D', value: 'D' }
                ],
                isMultiple: false,
                singleAnswer: 'A',   // 单选答案
                multipleAnswers: [],   // 多选答案（改为数组存储）
                referenceAnswer: 'A',   // 参考答案
                answerInfo: '',        // 答案解析
                knowledgePoints: []  // 新增：关联知识点数组
            }
        },
        {
            id: 2,
            content: '2',
            score: 10,
            info: {
                name: '选择2',
                description: '',
                type: 'choice',
                options: [
                    { label: '选项A', value: 'A' },
                    { label: '选项B', value: 'B' },
                    { label: '选项C', value: 'C' },
                    { label: '选项D', value: 'D' }
                ],
                isMultiple: true,
                singleAnswer: null,   // 单选答案
                multipleAnswers: ['C', 'D'],   // 多选答案（改为数组存储）
                referenceAnswer: 'C,D',   // 参考答案
                answerInfo: '',        // 答案解析
                knowledgePoints: []  // 新增：关联知识点数组
            }
        },            
    ],
    fill: [
       {
            id: 4,
            content: '4',
            score: 10,
            info: {
                name: '填空4',
                description: '',
                type: 'fill',
                options: [],
                isMultiple: true,
                singleAnswer: null,   // 单选答案/ 答案
                multipleAnswers: [],   // 多选答案（改为数组存储）
                referenceAnswer: 'C',   // 参考答案
                answerInfo: '',        // 答案解析
                knowledgePoints: []  // 新增：关联知识点数组
            }
        }, 

    ],
    answer: [

    {
            id: 4,
            content: '4',
            score: 30,
            info: {
                name: '解答4',
                description: '',
                type: 'answer',
                options: [],
                isMultiple: true,
                singleAnswer: null,   // 单选答案/ 答案
                multipleAnswers: [],   // 多选答案（改为数组存储）
                referenceAnswer: 'C',   // 参考答案
                answerInfo: '',        // 答案解析
                knowledgePoints: []  // 新增：关联知识点数组
            }
        },
    ],
  }
};

// 按题型分类题目
const choiceQuestions = ref(mockData.questions.choice);

const fillQuestions = ref(mockData.questions.fill);

const answerQuestions = ref(mockData.questions.answer);

// 总分
const totalScore = ref(0);

// 选择题分数
const choiceScores = ref(0); 
// 填空题分数
const fillScores = ref(0);
// 解答题分数
const answerScores = ref(0);

// 选择题总分
let choiceTotalScore = 0;
choiceQuestions.value.forEach(q => {
    choiceTotalScore += q.score;
  });
// 填空题总分
let fillTotalScore = 0;
fillQuestions.value.forEach(q => {
    fillTotalScore += q.score;
  });
// 解答题总分
let answerTotalScore = 0;
answerQuestions.value.forEach(q => {
    answerTotalScore += q.score;
  });



// 计算总分
const calculateScore = () => {
  let score = 0;
  
  // 选择题分数
  choiceQuestions.value.forEach(q => {
    if (checkChoiceAnswer(q.info)) score += q.score;
  });
  choiceScores.value = score;
  
  // 填空题分数
  fillQuestions.value.forEach(q => {
    if (q.judgment === 'correct') score += q.score;
  });
  fillScores.value = score - choiceScores.value;
  
  // 解答题分数
  answerQuestions.value.forEach(q => {
     
    if (q.judgment === 'correct') score += q.score;
  });
  // 简答题分数
  answerScores.value = score - choiceScores.value - fillScores.value;
  totalScore.value = score;
};

// 检查选择题答案是否正确
const checkChoiceAnswer = (questionInfo) => {
  let studentAnswer = questionInfo.singleAnswer;
  if (questionInfo.isMultiple) {
    studentAnswer = (questionInfo.multipleAnswers || []).join(',')
  }
  return questionInfo.referenceAnswer == studentAnswer;
};

function judgeCorrect (question) {
  if (question.info.type === 'choice') {
    return checkChoiceAnswer( question.info);
  } else if (question.info.type === 'fill') {
    return question.info.judgment === 'correct';
  } else if (question.info.type === 'answer') {
    return question.info.judgment === 'correct';
  }
}

// 取消
const cancelScores = () => {
  // 这里实现保存评分逻辑
  router.back()
};

// 提交评分
const submitScores = () => {
  // 这里实现提交评分逻辑
  console.log('提交评分');
  // 判断一下填空题和解答题，有没有判断答案，没有给出提示
  const fillUnjudgedIndex = fillQuestions.value.findIndex(q => !judgeCorrect(q));
  if (fillUnjudgedIndex > -1) {
    ElMessage.error(`请判断填空题${fillUnjudgedIndex + 1}答案`);
    return;
  }
  const answerUnjudgedIndex = answerQuestions.value.findIndex(q => !judgeCorrect(q));
  if (answerUnjudgedIndex > -1) {
    ElMessage.error(`请判断解答题${answerUnjudgedIndex + 1}答案`);
    return;
  }

  const params  = {
    choiceQuestions : choiceQuestions.value,
    fillQuestions : fillQuestions.value,
    answerQuestions : answerQuestions.value,
  }
 
};
</script>

<style scoped>
.scoring-container {
  padding: 20px;
  font-family: 'Microsoft YaHei', sans-serif;
}

.top-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.left-info, .right-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.right-info {
  align-items: flex-end;
}

.info-item {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  margin-right: 8px;
  color: #333;
}

.total-score {
  margin-top: 10px;
}

.score-value {
  color: #ff4d4f;
  font-size: 24px;
  font-weight: bold;
}

.bottom-section {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  height: calc(100vh - 300px);
}

.question-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
}

.column-title {
  display: flex;
  justify-content: space-around;
  background-color: #f0f2f5;
  margin: 0;
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
  font-size: 16px;
  color: #1f2937;
}

.question-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.question-item {
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  margin-bottom: 15px;
  background-color: #fff;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
  gap: 8px;
}

.question-number {
  font-weight: bold;
  color: #1f2937;
  min-width: 20px;
}

.question-score {
  color: #6b7280;
  margin-left: auto;
  font-weight: 500;
}

.judgment-buttons {
  display: flex;
  gap: 10px;
  margin-left: 10px;
}

.question-stem {
  line-height: 1.6;
  margin-bottom: 12px;
  color: #374151;
}

.question-options {
  margin-bottom: 15px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding-left: 5px;
}

.option-label {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  border-radius: 50%;
  background-color: #e5e7eb;
  margin-right: 10px;
  font-weight: 500;
}

.option-content {
  flex: 1;
}

.student-answer {
  margin-left: 10px;
}

.correct-answer {
  color: #52c41a;
  margin-left: 10px;
  font-size: 12px;
}

.answer-analysis, .knowledge-points, .student-answer, .reference-answer {
  margin-top: 12px;
  padding: 10px;
  background-color: #f9fafb;
  border-radius: 4px;
  font-size: 13px;
}

.teacher-comment {
  margin-top: 15px;
}

.knowledge-points {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.knowledge-tag {
  margin: 2px;
}

.bottom-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

/* 滚动条样式优化 */
.question-list::-webkit-scrollbar {
  width: 6px;
}

.question-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.question-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

.question-list::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
</style>